package com.spbdx.system.service.workflow;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson2.JSONObject;
import com.spbdx.system.domain.EventOrder;
import com.spbdx.system.mapper.EventOrderMapper;
import com.spbdx.system.service.workflow.support.MachineStatus;
import com.spbdx.system.service.workflow.support.MachineStatusEvent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.statemachine.StateMachine;
import org.springframework.statemachine.persist.StateMachinePersister;
import org.springframework.stereotype.Component;

/**
 * 状态转换工具类
 *
 * @author chenwei
 * @version 1.0
 * @date 2024/8/7 09:37
 */
@Component
public class StateEventUtil {
    @Autowired
    private StateMachine<MachineStatus, MachineStatusEvent> machineState;

    @Autowired
    private StateMachinePersister<MachineStatus, MachineStatusEvent, EventOrder> machinePersister;

    @Autowired
    private EventOrderMapper eventOrderMapper;

    /**
     * 维保单状态转换发送事件
     *
     * @param orderId 工单ID
     * @param event   MachineStatusEvent 枚举字符串
     * @return
     */
    public synchronized boolean sendEvent(Long orderId, String event, JSONObject jsonObj) {
        Assert.notEmpty(event, "事件不能为空");
        MachineStatusEvent machineStatusEvent;
        try {
            machineStatusEvent = MachineStatusEvent.valueOf(event.toUpperCase());
        } catch (Exception e) {
            throw new RuntimeException(event + " 事件不存在");
        }
        EventOrder eventOrder = eventOrderMapper.selectEventOrderByOrderId(orderId);
        Assert.notNull(eventOrder, "没有找到工单");
        Assert.notEmpty(eventOrder.getOrderStatus(), "工单状态为空，无法继续操作！");
        MachineStatus status = MachineStatus.valueOf(eventOrder.getOrderStatus().toUpperCase());
        boolean result = false;
        try {
            Message message = MessageBuilder.withPayload(machineStatusEvent).setHeader("eventOrder", eventOrder).setHeader("jsonObj", jsonObj).build();
            //启动状态机
            machineState.start();
            //尝试恢复状态机状态
            machinePersister.restore(machineState, eventOrder);
            result = machineState.sendEvent(message);
            Assert.isTrue(result, "流程节点错误，当前流程->" + status.getLabel() + "，无法继续操作！");
            //持久化状态机状态
            machinePersister.persist(machineState, eventOrder);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e.getMessage());
        } finally {
            machineState.stop();
        }
        return result;
    }

    public static void main(String[] args) {
        // 测试代码
        StateEventUtil util = new StateEventUtil();
        JSONObject object = new JSONObject();
        object.put("param", "");
        util.sendEvent(1L, "ACCEPT", object);
    }
}
